<template>
    <nav class="flex items-center justify-between p-4 bg-white shadow-md">
        <!-- 左边：Logo -->
        <div class="flex items-center">
            <img src="../assets/food-app-logo.jpg" alt="Logo" class="w-10 h-10 mr-3">
            <span class="text-2xl font-bold text-blue-600">味蕾旅行家</span>
        </div>

        <!-- 中间：导航项 -->
        <div class="flex space-x-6">
            <router-link to="/"
                class="text-gray-700 hover:text-white hover:bg-gray-900 px-3 py-1 rounded transition-colors duration-300"
                active-class="active">首页</router-link>
            <router-link to="/foodList"
                class="text-gray-700 hover:text-white hover:bg-gray-900 px-3 py-1 rounded transition-colors duration-300"
                active-class="active">美食列表</router-link>
            <router-link to="/recipeList"
                class="text-gray-700 hover:text-white hover:bg-gray-900 px-3 py-1 rounded transition-colors duration-300"
                active-class="active">菜谱列表</router-link>
            <router-link to="/user"
                class="text-gray-700 hover:text-white hover:bg-gray-900 px-3 py-1 rounded transition-colors duration-300"
                active-class="active">个人中心</router-link>
        </div>
        <div class="flex items-center space-x-8">
            <el-icon class="text-yellow-500 text-2xl" @click="changeBackground('ghostwhite')">
                <Sunny />
            </el-icon>
            <el-icon class="text-gray-900 text-2xl" @click="changeBackground('black')">
                <Moon />
            </el-icon>
        </div>
        <!-- 右边：登录和注册按钮 -->
        <div class="flex items-center space-x-4">
            <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link">
                    <el-avatar :size="30" :src="`http://localhost/storage/${store.state.user.avatar}`" />
                    {{ $store.state.user.username }}
                    <el-icon class="el-icon--right">
                        <arrow-down />
                    </el-icon>
                </span>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="rePassword">修改密码</el-dropdown-item>
                        <el-dropdown-item command="user">个人信息</el-dropdown-item>
                        <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>
        <el-drawer v-model="drawer" title="修改密码" size="45%" :close-on-click-outside="false">
            <!-- <span>Hi there!</span> -->
            <el-form :model="form" :rules="rules" ref="formRef" label-width="80px" size="small">
                <el-form-item prop="oldpassword" label="旧密码">
                    <el-input v-model="form.oldpassword" type="password" placeholder="请输入旧密码" show-password />
                </el-form-item>
                <el-form-item prop="password" label="新密码">
                    <el-input v-model="form.password" type="password" placeholder="请输入新密码" show-password />
                </el-form-item>
                <el-form-item prop="repassword" label="确认密码">
                    <el-input v-model="form.repassword" type="password" placeholder="请确认新密码" show-password />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
        <el-drawer v-model="draweruser" title="补充个人信息" size="45%" :close-on-click-outside="false">
            <el-form ref="formuser" :model="userInfo" :rules="rule" label-width="80px">
                <el-form-item label="头像" prop="avatar">
                    <!-- <el-upload  drag class="avatar-uploader" :action=updateImg :show-file-list="false" name="avatar"
                        :data="uploadData" :on-success="handleAvatarSuccess" >
                        <img v-if="userInfo.avatar" :src="`http://localhost/storage/${userInfo.avatar}`"
                            class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <div class="el-upload__text">
                            Drop file here or <em>click to upload</em>
                        </div>
                        <template #tip>
                            <div class="el-upload__tip">
                                jpg/png files with a size less than 500kb
                            </div>
                        </template>
                    </el-upload> -->
                    <el-upload drag :action=updateImg name="avatar" :data="uploadData">
                        <img v-if="userInfo.avatar" :src="`http://localhost/storage/${userInfo.avatar}`"
                            class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">
                                jpg/png files with a size less than 500kb
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userInfo.username" clearable></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="userInfo.sex" placeholder="请选择性别">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="userInfo.phone" clearable></el-input>
                </el-form-item>
                <el-form-item label="个性签名" prop="signature">
                    <el-input v-model="userInfo.signature" type="textarea"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="updateUserInfo">修改</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </nav>
</template>

<script setup>
import { RouterLink } from 'vue-router';
import { showModal } from '~/composables/util';
import { ElNotification } from 'element-plus';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex'
import { ref, reactive } from 'vue'
import { updatepassword, updateuser, updateImg } from '~/api/manager'
import { useCookies } from '@vueuse/integrations/useCookies';

const drawer = ref(false)
const draweruser = ref(false)
const router = useRouter()
const store = useStore()
const cookies = useCookies()

const form = reactive({
    user_id: '',
    oldpassword: '',
    password: '',
    repassword: '',
})
const userId = cookies.get('use_id');
const uploadData = reactive({ user_id: userId });
const formuser = ref(null)
const userInfo = reactive({
    avatar: store.state.user.avatar || '',
    username: store.state.user.username || '',
    sex: store.state.user.sex || '',
    phone: store.state.user.phone || '',
    signature: store.state.user.signature || ''
})

const rule = {
    username: [
        { required: true, message: '用户名不能为空', trigger: 'blur' }
    ],
    sex: [
        { required: true, message: '性别不能为空', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    signature: [
        { required: false, message: '个性签名可选', trigger: 'blur' }
    ]
}
const rules = {
    oldpassword: [
        { required: true, message: '旧密码不能为空', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '新密码不能为空', trigger: 'blur' },
        { min: 6, message: '长度至少6个字符', trigger: 'blur' }
    ],
    repassword: [
        { required: true, message: '确认新密码不能为空', trigger: 'blur' },
        { min: 6, message: '长度至少6个字符', trigger: 'blur' }
    ]
}
const formRef = ref(null)
const onSubmit = () => {
    formRef.value.validate(valid => {
        if (!valid) {
            return false;
        }
        const user_id = cookies.get("use_id")
        form.user_id = user_id
        console.log(form)
        updatepassword(form)
            .then(res => {
                if (res.code == 200) {
                    ElNotification({
                        message: "修改密码成功,请重新登录",
                        type: 'success',
                        duration: 3000
                    })
                    store.dispatch('logout')
                    //跳转登录页
                    router.push('/login')
                }
            });
    });
}

const changeBackground = (color) => {
    document.body.style.backgroundColor = color
}
const handleCommand = (c) => {
    switch (c) {
        case 'logout':
            handlogout()
            break;
        case "rePassword":
            drawer.value = true
            break;
        case "user":
            draweruser.value = true
            break;
    }
}
function handlogout() {
    showModal("是否退出登录？").then(res => {
        store.dispatch('logout')
        //跳转回登录页
        router.push('/login')
        // 提示退出成功
        ElNotification({
            message: "退出登录成功",
            type: 'success',
            duration: 3000
        })

    })
}
const updateUserInfo = () => {
    formuser.value.validate(valid => {
        if (!valid) {
            return false;
        }
        userInfo.user_id = cookies.get("use_id")
        const formData = new FormData();
        for (const key in userInfo) {
            formData.append(key, userInfo[key]);
        }
        console.log(formData);
        updateuser(formData)
            .then(res => {
                if (res.code == 200) {
                    ElNotification({
                        message: "修改成功",
                        type: 'success',
                        duration: 3000
                    });
                    draweruser.value = false;
                    // 刷新页面
                    location.reload();
                }
            });
    });
}

</script>


<style scoped>
.active {
    background-color: rgb(128, 128, 128);
    color: white;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>